package com.lv.service.dialog

import android.Manifest
import android.content.Context
import android.content.pm.ActivityInfo
import android.os.Build
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.fragment.app.FragmentActivity
import com.blankj.utilcode.util.KeyboardUtils
import com.bumptech.glide.Glide
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.lv.common.imp.DecimalInputTextWatcher
import com.lv.common.imp.OnPositionMoreArgsT
import com.lv.common.ktx.priceSmallDot
import com.lv.common.utils.*
import com.lv.common.utils.picengine.CompressEngine
import com.lv.common.utils.picengine.GlideEngine
import com.lv.service.R
import com.lxj.xpopup.impl.PartShadowPopupView

/**
 * 作者： ygx
 * 创建日期：2022/10/10 10:32 AM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 *
 *
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：广告编辑
 */
class AdEditorPopupView(
    private val mContext: Context,
    private val mTitle: String,
    private val topH: Int = 0,
    private val selectMedia: ArrayList<LocalMedia?>,
    private val price: String,
    private val mLayout: Int = R.layout.ad_editor_popup,
    private val mPositionTListener: OnPositionMoreArgsT<String, List<LocalMedia?>>? = null
) :
    PartShadowPopupView(mContext), View.OnClickListener {
    private val name = ""
    private var tvTitle: TextView? = null
    private var viewTop: View? = null
    private var viewShadow: TextView? = null
    private var tvCancel: TextView? = null
    private var ivClose: ImageView? = null
    private var ivPic: ImageView? = null
    private var ivAdd: ImageView? = null
    private var ivDelete: ImageView? = null
    private var etPrice: EditText? = null
    private var mPrice: String = ""
    private val mSelectMedia = mutableListOf<LocalMedia?>()
    override fun getImplLayoutId(): Int {
        return mLayout
    }

    override fun onCreate() {
        super.onCreate()
        mPrice = price
        tvTitle = findViewById<TextView>(R.id.tv_title)
        viewTop = findViewById<View>(R.id.view_top)
        viewShadow = findViewById<TextView>(R.id.tv_save)
        tvCancel = findViewById<TextView>(R.id.tv_cancel)
        ivClose = findViewById<ImageView>(R.id.iv_close)
        etPrice = findViewById<EditText>(R.id.et_price)
        ivPic = findViewById<ImageView>(R.id.iv_pic)
        ivAdd = findViewById<ImageView>(R.id.iv_add)
        ivDelete = findViewById<ImageView>(R.id.iv_delete)
        etPrice?.addTextChangedListener(DecimalInputTextWatcher(etPrice, 10, 2))
        etPrice?.setOnLongClickListener { true }
        val layoutParams = viewTop?.layoutParams as ConstraintLayout.LayoutParams
        layoutParams.height = topH
        initView()
        initEvnet()
    }

    private fun initView() {
        tvTitle?.text = mTitle
        if (mPrice.isNotEmpty()) {
            mPrice = MoneyUtil.moneydiv(mPrice, "100").priceSmallDot()
            etPrice?.setText(mPrice)
            etPrice?.setSelection(mPrice.length)
        }
        if (selectMedia.isNotEmpty()) {
            mSelectMedia.clear()
            mSelectMedia.addAll(selectMedia)
            var compressPath = mSelectMedia[0]?.compressPath
            if (compressPath.isNullOrEmpty()) {
                compressPath = mSelectMedia[0]?.realPath
            }
            Glide.with(mContext)
                .load(compressPath)
                .into(ivPic!!)
            ivAdd?.visibility = View.GONE
            ivDelete?.visibility = View.VISIBLE
        }
    }

    private fun initEvnet() {

        viewTop?.setOnClickListener(this)
        ivClose?.setOnClickListener(this)
        viewShadow?.setOnClickListener(this)
        ivPic?.setOnClickListener(this)
        ivDelete?.setOnClickListener(this)
        tvCancel?.setOnClickListener(this)
        etPrice?.setOnEditorActionListener { v, actionId, event ->
            KeyboardUtils.hideSoftInput(etPrice!!)
            true
        }
    }

    private fun showPicSelector() {

        PictureSelector.create(mContext)
            .openGallery(SelectMimeType.ofImage())
            .setImageEngine(GlideEngine.createGlideEngine())
            .setCompressEngine(CompressEngine.createCompressEngine())
            .setMaxSelectNum(1)
            .setMinSelectNum(1)
            .setImageSpanCount(4)
            .isPreviewImage(true) // 是否可预览图片
            .isDisplayCamera(true) // 是否显示拍照按钮
            .isOriginalSkipCompress(true) // 是否压缩
            .setSelectedData(mSelectMedia)
            .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
            .forResult(object : OnResultCallbackListener<LocalMedia?> {
                override fun onResult(result: ArrayList<LocalMedia?>?) {
                    result?.let {

                        mSelectMedia.clear()
                        mSelectMedia.addAll(it)
                        var compressPath = mSelectMedia[0]?.compressPath
                        if (compressPath.isNullOrEmpty()) {
                            compressPath = mSelectMedia[0]?.realPath
                        }
                        Glide.with(mContext)
                            .load(compressPath)
                            .into(ivPic!!)

                        ivAdd?.visibility = View.GONE
                        ivDelete?.visibility = View.VISIBLE
                    }
                }

                override fun onCancel() {}
            })


    }

    private fun checkPermission() {
        val permissions = mutableListOf(
            Manifest.permission.CAMERA,
        )
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            permissions.add(Manifest.permission.READ_MEDIA_IMAGES)
//            permissions.add(Manifest.permission.READ_MEDIA_AUDIO)
//            permissions.add(Manifest.permission.READ_MEDIA_VIDEO)
        } else {
            permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE)
        }
        PermissionXUtils.checkPermissBefore(
            mContext as FragmentActivity,
            permissions,
            "请授予相机、存储权限，以便使用相机拍摄或在手机相册中选择图片",
            callback = object : PermissionXUtilsCallback {
                override fun permissionCallback(
                    allGranted: Boolean,
                    grantedList: List<String?>,
                    deniedList: List<String?>
                ) {
                    if (allGranted) {
                        showPicSelector()
                    }
                }
            })
    }

    private fun setDismissDialog() {
        dismiss()
    }


    override fun onDestroy() {
        super.onDestroy()
    }

    override fun beforeDismiss() {
        super.beforeDismiss()


    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.view_top, R.id.iv_close, R.id.tv_cancel -> dismiss()
            R.id.tv_save -> {
                var mPrice = 0L
                val price = etPrice?.text?.trim().toString()
                if (price.isEmpty() && mSelectMedia.isEmpty()) {
                    showToast("请输入金额或选择图片")
                    return
                }
                if (price.isNotEmpty()) {
                    mPrice = MoneyUtil.moneyMulToLong(price, "100")
                    if (mPrice == 0L) {
                        showToast("请输入正确金额")
                        AnimationUtils.setHintAnimation(etPrice)
                        return
                    }
                }
//                if (price.isEmpty()) {
//                    showToast("请输入金额")
//                    AnimationUtils.setHintAnimation(etPrice)
//                    return
//                } else {
//                    mPrice = MoneyUtil.moneyMulToLong(price, "100")
//                    if (mPrice == 0L) {
//                        showToast("请输入金额")
//                        AnimationUtils.setHintAnimation(etPrice)
//                        return
//                    }
//                }
//                if (mSelectMedia.isEmpty()) {
//                    showToast("请选择图片")
//                    AnimationUtils.setHintAnimation(ivPic)
//                    return
//                }
                mPositionTListener?.onClick(0, v = if (mPrice==0L) "" else "$mPrice", v2 = mSelectMedia)
                dismiss()
            }
            R.id.iv_pic -> {
                checkPermission()
            }
            R.id.iv_delete -> {
                ivAdd?.visibility = View.VISIBLE
                ivDelete?.visibility = View.GONE
                Glide.with(mContext)
                    .load(0)
                    .into(ivPic!!)
                mSelectMedia.clear()
            }

        }
    }

}